package com.pdool.game.listener;

import com.pdool.common.constants.Constant;
import com.pdool.game.core.config.GameConfig;
import com.pdool.game.logic.mgr.UserMgr;
import com.pdool.game.logic.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 关服 监听
 */
@Component
@Slf4j
public class ShutDownListener implements ApplicationListener<ContextClosedEvent> {
    @Resource
    LoginService loginService;
    @Resource
    RedisTemplate redisTemplate;

    @Resource
    GameConfig gameConfig;
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        Map<Long, WebSocketSession> sessionMap = UserMgr.getInstance().getSessionMap();
        sessionMap.values().forEach(session -> {
            loginService.logOut(session);
        });
        redisTemplate.opsForHash().put(Constant.GAME_ONLINE_COUNT,gameConfig.getServerId(),0);
        log.error("关服 ---------");
    }
}
